<?php 
function authenticate_user($username,$password)
{
	$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
	if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}
	else
	{	
		$username = mysqli_real_escape_string($con,$username);
		$password = mysqli_real_escape_string($con,$password);
		$password = md5($password);
		$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
		$result = mysqli_query($con,$query);
		$num_row = mysqli_num_rows($result);
		mysqli_close($con);
		if($num_row > 0)
		{
			$_SESSION['loggedin']=1;
			return true;
		}
		else
		{
			return false;
		}
	}
}

function get_clicks()
{
	$con1 = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
	if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}
	else
	{	
		$sql = "SELECT clicks FROM coffee_clicks";
		if ($result=mysqli_query($con1,$sql))
		{
			while ($row=mysqli_fetch_row($result))
			{
				return $row[0];
			}
		}
	}
	mysqli_close($con1);
}

function get_contest_details($contest_id=0,$approved=null,$limit=0,$offset=0,$order='DESC')
{
	$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
	if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}
	else
	{
		$query = "SELECT * FROM contest";
		if(!empty($contest_id))
		{
			$contest_id = mysqli_real_escape_string($con,$contest_id);
			$query .= " WHERE id = $contest_id";
		}
		if(!empty($approved))
		{
			$query .= " WHERE approved = 1";
		}
		$query .= " ORDER BY id $order";
		if(!empty($limit))
		{
			$query .= " LIMIT $offset, $limit";
		}
		if ($result=mysqli_query($con,$query))
		{
			$contest = array();
			$i = 0;
			while ($row=mysqli_fetch_array($result))
			{
				$contest[$i]['id'] = $row['id'];
				$contest[$i]['name'] = $row['name'];
				$contest[$i]['phone'] = $row['phone'];
				$contest[$i]['email'] = $row['email'];
				$contest[$i]['message'] = $row['message'];
				$contest[$i]['picture'] = $row['picture'];
				$contest[$i]['approved'] = $row['approved'];
				$i++;
			}
		}
		mysqli_close($con);
		return $contest;
	}
}

if(isset($_GET['pagination']))
{
	exit(json_encode(get_contest_details($_GET['contest_id'],$_GET['approved'],$_GET['limit'],$_GET['offset'])));
	exit;
}

if(isset($_GET['id']) && isset($_GET['action']))
{
	//check if admin
	$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
	if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}
	else
	{	
		$id = mysqli_real_escape_string($con,$_GET['id']);
		$action = mysqli_real_escape_string($con,$_GET['action']);
		if($action == 'approve')
		{
			$status = 1;
		}
		if($action == 'unapprove')
		{
			$status = 0;		
		}
		mysqli_query($con,"UPDATE contest SET approved = $status WHERE id = $id");
		mysqli_close($con);
		header('Location:'.SITE_URL . 'admin/dashboard.php?admin_success=1');
	}
}

if(isset($_POST['contest_submit']))
{
	$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
	if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}
	else
	{
		$name = mysqli_real_escape_string($con,$_POST['name']);
		$phone = mysqli_real_escape_string($con,$_POST['phone']);
		$email = mysqli_real_escape_string($con,$_POST['email']);
		$message = mysqli_real_escape_string($con,$_POST['message']);
		$allowedExts = array("gif", "jpeg", "jpg", "png","GIF","JPEG","JPG","PNG");
		$temp = explode(".", $_FILES["imagefile"]["name"]);
		$extension = end($temp);
		if ((($_FILES["imagefile"]["type"] == "image/gif")
		|| ($_FILES["imagefile"]["type"] == "image/jpeg")
		|| ($_FILES["imagefile"]["type"] == "image/jpg")
		|| ($_FILES["imagefile"]["type"] == "image/pjpeg")
		|| ($_FILES["imagefile"]["type"] == "image/x-png")
		|| ($_FILES["imagefile"]["type"] == "image/png"))
		&& ($_FILES["imagefile"]["size"] < 10000000)
		&& in_array(strtolower($extension), $allowedExts)) 
		{
			if ($_FILES["imagefile"]["error"] > 0)
			{
		    	echo "Return Code: " . $_FILES["imagefile"]["error"] . "<br>";
		    } 
		    else 
		    {	      		
				$newfile = explode(".",$_FILES["imagefile"]["name"]);
				$imagefile = $newfile[0] . "_" . uniqid('img') . "." . end($newfile);
				
				$orginalImagePath = 'upload/' . $imagefile;
		      	if(move_uploaded_file($_FILES["imagefile"]["tmp_name"],$orginalImagePath))
		      	{
			      	require_once 'includes/simple_image.php';
					$file_location = '/var/www/yourwebsite/uploads/'; # Image folder Path
					$imageSimpleImage = new SimpleImage();	
					
					$imageSimpleImage->load($orginalImagePath);
					$imageSimpleImage->resizeToWidth(350);
					$standardImagePath = 'upload/standard/' . $imagefile;
					$imageSimpleImage->save($standardImagePath);
					
					$imageSimpleImage->load($orginalImagePath);					
					$imageSimpleImage->resizeToWidth(130);
					$thumbImagePath = 'upload/thumb/' . $imagefile;
					$imageSimpleImage->save($thumbImagePath);
					
					$picture = $imagefile;
			      	$query = "INSERT INTO contest VALUES (NULL, '$name', $phone, '$email', '$message', '$picture',0)";
			      	mysqli_query($con,$query);
					$_SESSION['contest_submit'] = 1;
			      	header('Location:'. SITE_URL.'?status=success&contest_id='.mysqli_insert_id($con));
					exit;
					
			    }
			}
		}
		else
		{
			header('Location:'. SITE_URL.'?status=error&errorname=Invalid File');
		}
		
	}
}

if(isset($_GET['logout']))
{
	unset($_SESSION['loggedin']);
	header('Location:'. SITE_URL);
}

?>